package com.wchat.auth;

import com.wchat.dataobject.UserEntity;
import com.wchat.enums.ResultEnum;
import com.wchat.exceptions.ServiceException;
import com.wchat.repository.UserRepository;
import com.wchat.service.AuthUtilService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AuthInterceptor implements HandlerInterceptor {

   private static final String SERVER_CONTEXT_PATH = "/romance";
   private AntPathMatcher antPathMatcher = new AntPathMatcher();
   @Autowired private UserRepository userRepository;

    @Autowired
    private AuthUtilService authUtilService;

    enum ResourceType{
        USER
    }

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        AuthUtilService.AuthInfo authInfo = null;  //  用户信息载体

         String requestToken = httpServletRequest.getParameter(AuthUtilService.requestTokenKey);
         if(requestToken != null ) {
             authInfo = authUtilService.decryptFromJwt(requestToken); //  解密token获取用户信息载体
         }if(authInfo == null){
             authInfo = (AuthUtilService.AuthInfo) httpServletRequest.getSession().getAttribute(AuthUtilService.sessionKey);
          }else {
             httpServletRequest.getSession().setAttribute(AuthUtilService.sessionKey,authInfo);
        }
        ResourceType resourceType = getResourceType(httpServletRequest.getRequestURI());
//        if(authInfo == null){
//            if(resourceType.equals(ResourceType.USER)){
//                return true;
//            }
//            httpServletResponse.setStatus(401);
//        }
        if(resourceType.equals(ResourceType.USER)){
            UserEntity userEntity = userRepository.findOne(authInfo.userId);
            if(userEntity != null && userEntity.getIsNew() == 1){
                throw new ServiceException(ResultEnum.NO_VERIFIED.getCode(),ResultEnum.NO_VERIFIED.getValue()); // 该用户还无法登录 需要线下审核后方可登录
            }
            return true;

        }
        httpServletResponse.setStatus(401);
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }


    private ResourceType getResourceType(String uri){
          if(antPathMatcher.match(SERVER_CONTEXT_PATH + "/user/**",uri)){
              return ResourceType.USER;
          }
          return null;
    }
}
